#include "udpServer.hpp"
#include "onlineUser.hpp"
#include <cstdio>
#include <memory>
#include <fstream>
#include <signal.h>
#include <unordered_map>
using namespace std;
using namespace Server;
static void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << " local_port\n\n";
}
OnlineUser onlineUser;
void routeMessage(int sockfd, string clientip, uint16_t clientport, string message)
{
    if (message == "online")
    {
        onlineUser.addUser(clientip, clientport);
    }
    if (message == "offline")
    {
        onlineUser.delUser(clientip, clientport);
    }
    if (onlineUser.isOnline(clientip, clientport))
    {
        onlineUser.broadcastMessage(sockfd, clientip, clientport, message);
    }
    else
    {
        struct sockaddr_in client;
        bzero(&client, sizeof(client));
        client.sin_family = AF_INET;
        client.sin_port = htons(clientport);
        client.sin_addr.s_addr = inet_addr(clientip.c_str());
        string response = "你还没有上线, 请先上线, 运行: online";
        sendto(sockfd, response.c_str(), response.size(), 0, (struct sockaddr *)&client, sizeof(client));
    }
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    unique_ptr<udpServer> usvr(new udpServer(routeMessage, port));
    usvr->initServer();
    usvr->start();
    return 0;
}